#!/bin/bash

set -o errexit

UNAME=$(uname -s)
NODE=node
TOP=$(unset CDPATH; cd $(dirname $0)/../; pwd)
NODEUNIT="${TOP}/test/node_modules/nodeunit/bin/nodeunit"

if [[ $UNAME == "SunOS" ]]; then
    NODE=/usr/node/0.10/bin/node
fi

function usage
{
    echo "Usage:"
    echo "  runtest [OPTIONS...] file"
    echo ""
    echo "Options:"
    echo "  -r REPORTER  Nodeunit test reporter to use (default is 'tap')."
}

# Options
opt_reporter=tap

while getopts "hr:" opt
do
    case "$opt" in
        h)
            usage
            exit 0
            ;;
        r)
            opt_reporter=$OPTARG
            ;;
        *)
            usage
            exit 1
            ;;
    esac
done

# Should have only one argument left.
if [[ $OPTIND -ne $# ]]; then
    usage
    exit 1
fi

if [[ $UNAME == "SunOS" ]]; then
    echo "# Adding images.joyent.com as an imgadm source"
    imgadm sources -a "https://images.joyent.com/"

    for IMG in $(/usr/node/bin/node -e "console.log(require('/usr/fw/test/lib/vm').imageUUIDs.join(' '));"); do
        echo "# Installing required image $IMG"
        imgadm import $IMG
    done
fi

shift $(($OPTIND - 1))
$NODE $NODEUNIT --reporter $opt_reporter $1
